package com.wlts.wzy.TestDemo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.kuaishou.merchant.open.api.KsMerchantApiException;
import com.kuaishou.merchant.open.api.client.AccessTokenKsMerchantClient;
import com.kuaishou.merchant.open.api.client.oauth.OauthAccessTokenKsClient;
import com.kuaishou.merchant.open.api.client.oauth.OauthCredentialKsClient;
import com.kuaishou.merchant.open.api.request.KsMerchantExpressTemplateListRequest;
import com.kuaishou.merchant.open.api.request.KsMerchantItemAddRequest;
import com.kuaishou.merchant.open.api.request.KsMerchantItemCategoryRequest;
import com.kuaishou.merchant.open.api.request.KsMerchantOrderListRequest;
import com.kuaishou.merchant.open.api.request.param.item.MerchantServiceRuleParam;
import com.kuaishou.merchant.open.api.request.param.item.MerchantSkuInfoParam;
import com.kuaishou.merchant.open.api.response.*;
import com.kuaishou.merchant.open.api.response.oauth.KsAccessTokenResponse;
import com.kuaishou.merchant.open.api.response.oauth.KsCredentialResponse;
import com.kuaishou.merchant.open.api.response.view.order.MerchantOrderInfoView;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoField;
import java.util.ArrayList;
import java.util.List;

public class TestKSDemo {

    private static final String appKey = "ks664280946453531393";
    private static String appSecret = "JI3J6CTxjDMa7RD8BPm_0Q";
    private static String grantCode = "3d5ee974a93aa4404335c4d3e9a1773d02ea1445c65b965a724f440d8b85696191e747f4";
    private static String signSecret = "554a351fd517a39d6860d91d29b92a13";

    private static String accessToken = "ChFvYXV0aC5hY2Nlc3NUb2tlbhJgko1J5AKWYrQkgWwzaE3gdxfnMM0T7rSTPBKQkqydC1ZxRsRCVmHJpyIiUAyGn21AGUBq-ybYhfIDsnqQyZWmwXzXj1g20dBTCeDuvRGRjDgg_SQD4V_jhq_I7Y_JMeHLGhIUJin3hnZBFYAERUiTeEwxp4IiIBDvYt94achXwqIexubo-LAaI8Db8Io9RKJRXsYPHv_4KAUwAQ";
    private static OauthCredentialKsClient oauthCredentialKsClient;

    static {
        oauthCredentialKsClient
                = new OauthCredentialKsClient(appKey, appSecret);
    }


//{"accessToken":"ChFvYXV0aC5hY2Nlc3NUb2tlbhJQ6PlEkbijKv7FJdePtBu2hQv_141ZU-ThCX-CBQFpnmM06uVEGwgFMH2dcmo_0iGUHxpvmjYgk_A_0pDdbFegyxKFxMYLFzE08Vav0FbYKLoaEjaG1EF40kmyhTan331dUWILHyIg5Igpy8WzZyefvLzxbT0rzDcNFbCmd3wl2zzfRoKmvhcoBTAB",
// "expiresIn":172800,
// "openId":"f198e5b1f42978d414bf5724a7e9ad48",
// "refreshToken":"ChJvYXV0aC5yZWZyZXNoVG9rZW4SoAE1N8k73_uvuj52Pf51VieXx0-T4bJrTkPTRfrjGwrx0DCh0-3ZHOYTwCn8UDApMk-vsXsY5Sl8AUnYQjShMXOrbtRkaM2usA94dMuySU7IS1jrVtQzkMRQDXMUOTpYxWE2Ayzm1cqSMTVeB6yZ1KL6njhHhwFQnqes5VnYNLlvb_uDNN5kp7vIA0LEIbROQcljDK-df_wLWuJt9V5j5R6LGhJh5rh6geyFqE2aruT5TwaBdSsiIPcyzIgJqX9gu6aUkXq9KIAWxgnJy6lUq-1y9IRmmOJUKAUwAQ",
// "result":1}
    /**
     * 获得token
     */
    public void getToken() {

        OauthAccessTokenKsClient oauthAccessTokenKsClient
                = new OauthAccessTokenKsClient(appKey, appSecret);

// 生成AccessToken
        try {
            KsAccessTokenResponse response
                    = oauthAccessTokenKsClient.getAccessToken(grantCode);
            System.out.println(JSON.toJSONString(response));
            accessToken = response.getAccessToken();
        } catch (KsMerchantApiException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获得token
     */
    public void getToken2() {

        OauthCredentialKsClient oauthCredentialKsClient
                = new OauthCredentialKsClient(appKey, appSecret);

// 生成AccessToken
        try {
            KsCredentialResponse response
                    = oauthCredentialKsClient.getAccessToken();
            System.out.println(JSON.toJSONString(response));
            accessToken = response.getAccessToken();
        } catch (KsMerchantApiException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获得订单模板
     * @throws KsMerchantApiException
     */
    public void Expresstemplate() throws KsMerchantApiException {
        KsMerchantExpressTemplateListRequest request = new KsMerchantExpressTemplateListRequest();
        request.setAccessToken(accessToken);
        request.setLimit(5);
        request.setOffset(1);
        request.setSearchUsed(true);
        AccessTokenKsMerchantClient tokenKsMerchantClient
                = new AccessTokenKsMerchantClient("", appKey, signSecret);
        KsMerchantExpressTemplateListResponse response = tokenKsMerchantClient.execute(request);
        System.out.println(JSON.toJSONString(response));
    }

    /**
     * 产品分类
     * @throws KsMerchantApiException
     */
    public void category() throws KsMerchantApiException {

        KsMerchantItemCategoryRequest ksMerchantItemCategoryRequest = new KsMerchantItemCategoryRequest();
        ksMerchantItemCategoryRequest.setAccessToken(accessToken);
        AccessTokenKsMerchantClient tokenKsMerchantClient
                = new AccessTokenKsMerchantClient("", appKey, signSecret);

        KsMerchantItemCategoryResponse ksMerchantItemCategoryResponse = tokenKsMerchantClient.execute(ksMerchantItemCategoryRequest);

        System.out.println(JSON.toJSONString(ksMerchantItemCategoryResponse));

    }

    /**
     * 增加商品
     * @throws KsMerchantApiException
     */
    public void addGoods() throws KsMerchantApiException {

        //{"itemId":630215920636,
        // "itemTitle":"微波炉食物收纳盒保鲜盒冰箱杂粮水果蔬菜储物盒10件套",
        // "mainPicUrl":"//img.alicdn.com/imgextra/i2/2201498506788/O1CN01lV9fwQ200x7tuX3Sr_!!2-item_pic.png",
        // "reservePrice":2990,
        // "categoryId":50000567,
        // "canSell":false,
        // "taobaoShopName":"虾选旗舰店",
        // "extJson":"null",
        // "lmItemId":"10000102-630215920636",
        // "skuList"
        // :[{"skuId":4491724553261,
        // "skuPicUrl":"//img.alicdn.com/imgextra/i3/2201498506788/O1CN01vuNCv7200x80tUdyt_!!2201498506788.jpg",
        // "skuTitle":"10件套",
        // "priceCent":1560,
        // "points":0,
        // "pointsAmount":0,
        // "canSell":false,
        // "customizedAttributeMap":{},
        // "gradePriceModels":[],
        // "userLabelList":[]},
        // {"skuId":4496733077794,"skuPicUrl":"//img.alicdn.com/imgextra/i4/2201498506788/O1CN014TZa7F200x85whizi_!!2201498506788.jpg","skuTitle":"保鲜盒10件套（备用）","priceCent":1560,"points":0,"pointsAmount":0,"canSell":false,"customizedAttributeMap":{},"gradePriceModels":[],"userLabelList":[]}]}

        KsMerchantItemAddRequest goods = new KsMerchantItemAddRequest();
        goods.setAccessToken(accessToken);
        goods.setRelItemId(630215920637L);
        goods.setTitle("微波炉食物收纳盒保鲜盒冰箱杂粮水果蔬菜储物盒");

        //{"categoryId":1125,"categoryName":"生活日用","categoryPid":1124}

        List<String> array = new ArrayList<>();
        array.add("https://img.alicdn.com/imgextra/i2/2201498506788/O1CN01lV9fwQ200x7tuX3Sr_!!2-item_pic.png");
        goods.setImageUrls(array);
        goods.setDetails("微波炉食物收纳盒保鲜盒冰箱杂粮水果蔬菜储物盒");
        goods.setExpressFee(0);

        MerchantServiceRuleParam ruleParam = new MerchantServiceRuleParam();
        ruleParam.setRefundRule("1");
     //   ruleParam.setTheDayOfDeliverGoodsTime(9);
        ruleParam.setPromiseDeliveryTime(172800);
        ruleParam.setDepositRule("1");

        goods.setServiceRule(ruleParam);
        goods.setCategoryId(1125);
        goods.setCategoryName("生活日用");
        goods.setParentCategoryId(1124);
        goods.setParentCategoryName("居家日用");

        List<MerchantSkuInfoParam> skuList = new ArrayList<>();

        MerchantSkuInfoParam param = new MerchantSkuInfoParam();

        param.setRelSkuId(4491724553261L);
        param.setImageUrl("https://img.alicdn.com/imgextra/i3/2201498506788/O1CN01vuNCv7200x80tUdyt_!!2201498506788.jpg");
        param.setSkuSpecification("10件套");
        param.setSkuStock(2L);
        param.setSkuSalePrice(1560L);
        skuList.add(param);

        goods.setSkuInfoParams(skuList);

        goods.setExpressTemplateId(5995512890L);
        // goods.setCategoryId("");


        AccessTokenKsMerchantClient tokenKsMerchantClient
                = new AccessTokenKsMerchantClient("", appKey, signSecret);

        KsMerchantItemAddResponse response= tokenKsMerchantClient.execute(goods);

        //    KsMerchantItemCategoryResponse ksMerchantItemCategoryResponse = tokenKsMerchantClient.execute(ksMerchantItemCategoryRequest);

        System.out.println(JSON.toJSONString(response));

    }

    /**
     * 查询订单
     * @throws KsMerchantApiException
     */
    public void orderPcursorList() throws KsMerchantApiException {


        KsMerchantOrderListRequest orderListRequest = new KsMerchantOrderListRequest();
        orderListRequest.setAccessToken(accessToken);
        orderListRequest.setType(1);
        orderListRequest.setCpsType(0);
        orderListRequest.setSort(1);
        orderListRequest.setQueryType(1);
        long end = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();

        long start = LocalDateTime.now().minusDays(1).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        long timestamp = LocalDate.now().minusDays(1).atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();

        System.out.println(start);
        System.out.println(end);
        System.out.println(timestamp);

        orderListRequest.setBeginTime(start);

        orderListRequest.setEndTime(end);

        AccessTokenKsMerchantClient tokenKsMerchantClient
                = new AccessTokenKsMerchantClient("", appKey, signSecret);

        KsMerchantOrderListResponse response= tokenKsMerchantClient.execute(orderListRequest);

        List<MerchantOrderInfoView> orderInfoViews= response.getMerchantOrderListData().getOrderInfoList();

        orderInfoViews.forEach(a->{
            System.out.println("-----------------");
            System.out.println(JSON.toJSONString(a));
            System.out.println("-----------------");
        });

        //   {"activityType":1,"address":"{\"consignee\":\"杨生\",\"mobile\":\"15920194820\",\"provinceCode\":31,\"province\":\"上海市\",\"cityCode\":3101,\"city\":\"市辖区\",\"districtCode\":310101,\"district\":\"黄浦区\",\"address\":\"1104\"}","buyerId":0,"cpsType":1,"createTime":1611662613979,"discountFee":0,"expressFee":0,"mobile":"15920194820","num":1,"oid":2102600042684594,"orderProductInfoList":[{"buyerId":0,"createTime":1611662613981,"discountFee":0,"id":8034731858594,"itemId":909561092290,"itemLinkUrl":"https://app.kwaixiaodian.com/merchant/shop/detail?id=909561092290&hyId=kwaishop&layoutType=4","itemPicUrl":"https://ali-ec.static.yximgs.com/ufile/adsocial/2d848361-6f94-49c4-9db5-6650d4993a60.jpg","itemTitle":"微波炉食物收纳盒保鲜盒冰箱杂粮水果蔬菜储物盒","itemType":1,"num":1,"oid":2102600042684594,"originalPrice":1560,"price":1560,"refundId":0,"refundStatus":0,"relItemId":630215920637,"relSkuId":4491724553261,"skuDesc":"10件套","skuId":909561093290,"updateTime":1611662613981}],"payTime":1611662627048,"payType":1,"promiseTimeStampOfDelivery":1611835427048,"refund":0,"refundTime":0,"remark":"","sellerId":2117889290,"sellerNick":"绿账优品","sellerNoteList":[],"sendTime":0,"status":30,"theDayOfDeliverGoodsTime":120,"totalFee":1560,"updateTime":1611662630856}

        System.out.println(JSON.toJSONString(response));

    }

//https://s.kwaixiaodian.com/oauth/authorize?appId=ks664280946453531393&redirect_uri=http://rep.lvzhangkeji.com&scope=user_info,merchant_user,merchant_refund,merchant_order,merchant_logistics,merchant_item&response_type=code&state=161216769051311


    public static void main(String[] args) throws Exception {
        TestKSDemo demo = new TestKSDemo();
      //       demo.getToken();
        //   demo.getToken2();
        //demo.category();
//        demo.Expresstemplate();
   //     demo.addGoods();
   //     demo.orderPcursorList();
    }

}
